import Vue from 'vue'
import wx from 'weixin-js-sdk'
import store from '../store'

const getCookie = name => {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
  if (match) return match[2]
}

const setCookie = (name, value, expires) => {
  document.cookie = name + '=' + (value || '') + expires + '; path=/'
}

const urlParam = param => {
  const a = new RegExp('(\\?|&)' + param + '=([^&\\?]*)').exec(location.search)
  if (!a) return ''
  return RegExp.$2
}

const ALL_JS_API_LIST = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo',
  'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice',
  'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage',
  'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu',
  'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode',
  'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard']

// 初始化微信js配置
const initWxJs = async () => {
  if (Vue.prototype.$wx) return
  try {
    const data = (await Vue.prototype.$http.get('/biaobeihy/wx/signature?token=' + store.getters.token,
      {
        url: location.href.split('#')[0]
      })).data
    Vue.prototype.$wx = wx
    console.log(data)
    await wx.config({
      ...data,
      timestamp: data.timestamp || data.timeStamp,
      jsApiList: ALL_JS_API_LIST
    })
  } catch (e) {
    console.log(e)
  }
}

export default {
  getCookie,
  setCookie,
  urlParam,
  initWxJs
}
